/**
 * @version $Id$
 */
package org.spacegame.server;

import java.io.IOException;
import java.io.Serializable;

import org.spacegame.common.EntityState;
import org.spacegame.common.ObjectReceivedEvent;
import org.spacegame.common.ObjectReceivedListener;

/**
 * TODO Describe the type.
 * 
 * @author vincent
 * 
 */
public class Server extends Thread {

	private final ServerCommunicator serverCommunicator;

	/**
	 * TODO Describe the constructor.
	 * 
	 * @param serverCommunicator
	 */
	public Server(final ServerCommunicator serverCommunicator) {
		super("ServerThread");
		this.serverCommunicator = serverCommunicator;
	}

	@Override
	public void run() {
		serverCommunicator.addObjectReceivedListener(new ObjectReceivedListener() {

			@Override
			public void objectReceived(final ObjectReceivedEvent event) {
				final Serializable object = event.getObject();
				if (object instanceof EntityState) {
					final EntityState clientState = (EntityState) object;
					System.out.println("Server peer: " + event.getRemoteAddress());
					System.out.println("Server received: " + clientState);
				}
				final EntityState serverState = new EntityState(System.currentTimeMillis(), 1, 2, 3, 4, 5);
				System.out.println("Server sending: " + serverState);
				try {
					serverCommunicator.send(serverState);
				} catch (final IOException e) {
					e.printStackTrace();
				}
			}
		});
		// TODO TBD.
	}

}
